package com.company.cloud.official.modules.sdk.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.company.cloud.official.modules.sdk.response.AccessTokenEntity;
import com.company.cloud.sdk.core.config.WxApiConfig;
import com.company.cloud.sdk.core.constant.SdkReturnEnum;
import com.company.cloud.sdk.core.utils.StringUtils;

import java.util.Map;

public class OfficialWxApi {

    /*获取access_token*/
    private static final String GETTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}";

    /**
     * 获取access_token
     * @param config
     * @return
     */
    public static AccessTokenEntity getToken(WxApiConfig config){
        String url= getTokenUrl(config);
        if (StringUtils.isEmpty(url)) {
            return AccessTokenEntity.error(SdkReturnEnum.WX_Cofig_ERROR, new AccessTokenEntity());
        }
        String result = HttpUtil.get(url);
        if(StringUtils.isEmpty(result)) {
            return AccessTokenEntity.error(SdkReturnEnum.WX_OpenID_Read_Error, new AccessTokenEntity());
        }
        Map<String,String> resultMap= JSON.parseObject(result, Map.class);
        String accessToken=resultMap.get("access_token");
        if(StringUtils.isEmpty(accessToken)) {
            return AccessTokenEntity.error(SdkReturnEnum.WX_OpenID_Read_Error, new AccessTokenEntity());
        }
        return AccessTokenEntity.ok(new AccessTokenEntity(accessToken));
    }

    /**读取JSCODE2SESSION_URL*/
    public static String getTokenUrl(WxApiConfig config) {
        if(config!=null
                && !StringUtils.isEmpty(config.getWxAppID())
                && !StringUtils.isEmpty(config.getWxAppSecret())) {
            String url= StrUtil.format(GETTOKEN_URL, config.getWxAppID(),config.getWxAppSecret());
            return url;
        } else {
            return "";
        }
    }

//    public static void main(String[] args) {
//        WxApiConfig config = new WxApiConfig();
//        config.setCorpid("wxe5bb3017fd108c5d");
//        config.setCorpsecret("c1d31167a5edc9c66772bea7009ee160");
//        AccessTokenEntity entity = getToken(config);
//        System.out.println(JSONObject.toJSONString(entity));
//    }

}
